import { useDispatch, useSelector } from "react-redux";
import './style/index.scss'
import type { RootState } from '../../../store'
import { Tabs } from 'antd'
import { useEffect, useState } from 'react'
import { useLocation, useNavigate } from "react-router-dom";
import { searchRoute } from '../../../utils/utils'
import { routerArray } from '../../../routers'
import { setTabsList } from '../../../store/modules/tabs'
import { HOME_URL } from "../../../constants";
import MoreButton from './components/MoreButton'

const LayoutTabs = () => {
  const { themeConfig } = useSelector((state: RootState) => state.global)
  const { tabsList } = useSelector((state: RootState) => state.tabs)
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const { pathname } = useLocation()
  const [activeValue, setActiveValue] = useState<string>(pathname)

  // click tabs
  const clickTabs = (path: string) => {
    navigate(path)
  }

  //delete tabs
  const delTabs = (tabPath?: string) => {
    if (tabPath === HOME_URL) return
    if (pathname === tabPath) {
      tabsList?.forEach((item: any, index: number) => {
        if (item.key !== tabPath) return
        const nextTab = tabsList[index + 1] || tabsList[index - 1]
        if (!nextTab) return
        navigate(nextTab.key)
      })
    }
    dispatch(setTabsList(tabsList?.filter((item) => item.key !== tabPath)))
  }

  //add tabs
  const addTabs = () => {
    const route = searchRoute(pathname, routerArray)
    const newTabsList = JSON.parse(JSON.stringify(tabsList))

    if ((tabsList ?? []).every((item: any) => item.key !== route.path)) {
      newTabsList.push({
        label: route.meta!.title,
        key: route.path,
      })
    }
    dispatch(setTabsList(newTabsList))
    setActiveValue(pathname)      
  }

  useEffect(() => {
    addTabs()
  }, [pathname])

  return (
    <>
      {
        !themeConfig.tabs && (
          <div className="tab">
            <Tabs
              animated
              hideAdd
              activeKey={activeValue}
              items={tabsList}
              onChange={clickTabs}
              type='editable-card'
              onEdit={path => {
                delTabs(path as string)
              }}
            />
            <MoreButton tabsList={tabsList} delTabs={delTabs} />
          </div>
        )
      }
    </>
  )
};

export default LayoutTabs